<?php

namespace app\index\controller;

use app\common\controller\Frontend;
use app\common\library\Token;
use think\Db;
use EasyWeChat\Payment\Order as WechatOrder;

class Order extends Frontend
{

    protected $noNeedLogin = '*';
    protected $noNeedRight = '*';
    protected $layout = '';

    public function _initialize()
    {
        parent::_initialize();
    }

    public function index()
    {
        $list = Db::name('order')->where(['user_id' => $this->user['id']])->paginate(10);
        $this->assign('list', $list);
        $this->assign('title', '我的订单');
        return $this->view->fetch();
    }

    public function pay()
    {
        if(request()->isPost()) {
            $lesson_id = $this->request->param('lesson_id');
            $coupon_id = $this->request->param('coupon_id');
            $lesson = Db::name('lesson')->find($lesson_id);
            if(!$lesson) {
                $this->error('课程不存在！');
            }
            $coupon = Db::name('coupon')->where(['id' => $coupon_id])->find();
            $price = $lesson['price'];

            $time = time();
            $order_id = date('YmdHis') . str_pad(mt_rand(1, 99999), 5, '0', STR_PAD_LEFT);
            if($coupon && !$coupon['is_use']) {
                $price = $lesson['price']-$coupon['price'];
                if($price <= 0) {
                    // 创建平台订单
                    $orderData = [
                        'user_id' => $this->auth->id,
                        'goods_id' => $lesson['id'],
                        'type' => 1,
                        'order_id' => $order_id,
                        'price'    => $price,
                        'create_time' => $time,
                        'pay_time' => $time,
                        'status' => 1
                    ];
                    Db::name('coupon')->where(['id' => $coupon_id])->update(['is_use'=>1]);
                    Db::name('order')->insert($orderData);
                    $this->success('购买成功', url('lesson/today'));
                }
            }

            // 创建平台订单
            $orderData = [
                'user_id' => $this->auth->id,
                'goods_id' => $lesson['id'],
                'type' => 1,
                'order_id' => $order_id,
                'price'    => $price,
                'create_time' => $time
            ];
            // 创建微信订单
            $payment = $this->app->payment;
            $attributes = [
                'trade_type'       => 'JSAPI', // JSAPI，NATIVE，APP...
                'body'             => $lesson['name'],
                'detail'           => $lesson['name'],
                'out_trade_no'     => $order_id,
                'total_fee'        => $price*100, // 单位：分
                'openid'           => $this->auth->openid,
            ];

            $order = new WechatOrder($attributes);
            // 统一下单
            $result = $payment->prepare($order);
            if ($result->return_code == 'SUCCESS' && $result->result_code == 'SUCCESS'){
                Db::name('order')->insert($orderData);
                $prepayId = $result->prepay_id;
                $json = $payment->configForPayment($prepayId);
                $this->assign('json', $json);
                $this->assign('lesson', $lesson);
                $this->assign('title', '确认订单');
                return $this->view->fetch();
            }else{
                halt($result);
            }
        }
    }

    public function confirm()
    {
        $lesson_id = $this->request->param('lesson_id');
        $lesson = Db::name('lesson')->find($lesson_id);
        if(!$lesson) {
            $this->error('课程不存在！');
        }
        $this->assign('lesson', $lesson);
        $this->assign('title', '确认订单');
        return $this->view->fetch();
    }

    public function pay_goods()
    {
        if(request()->isPost()) {
            $params = $this->request->param();
            $goods = Db::name('goods')->where(['status' => 1])->find($params['goods_id']);
            if(!$goods) {
                $this->error('商品不存在或已下架！');
            }

            $time = time();
            $order_id = date('YmdHis') . str_pad(mt_rand(1, 99999), 5, '0', STR_PAD_LEFT);
            // 创建平台订单
            $orderData = [
                'user_id' => $this->auth->id,
                'goods_id' => $goods['id'],
                'order_id' => $order_id,
                'price'    => $goods['price'],
                'address_id' => $params['address_id'],
                'type' => 2,
                'create_time' => $time
            ];
            // 创建微信订单
            $payment = $this->app->payment;
            $attributes = [
                'trade_type'       => 'JSAPI', // JSAPI，NATIVE，APP...
                'body'             => $goods['name'],
                'detail'           => $goods['name'],
                'out_trade_no'     => $order_id,
                'total_fee'        => $goods['price'] * $params['goods_num'] * 100, // 单位：分
                'openid'           => $this->auth->openid,
            ];

            $order = new WechatOrder($attributes);
            // 统一下单
            $result = $payment->prepare($order);
            if ($result->return_code == 'SUCCESS' && $result->result_code == 'SUCCESS'){
                Db::name('order')->insert($orderData);
                $prepayId = $result->prepay_id;
                $json = $payment->configForPayment($prepayId);
                $this->assign('json', $json);
                $this->assign('title', '微信支付');
                return $this->view->fetch();
            }else{
                $this->error('支付错误');
            }
        }
    }


    public function info($goods_id)
    {
        $uid = $this->auth->id;
        $goods = Db::name('goods')->where(['id' => $goods_id, 'status' => 1])->find();
        if(!$goods) {
            $this->error('该商品不存在或已下架！');
        }
        $address = Db::name('address')->where(['uid' => $uid, 'is_default' => 1])->find();
        if(!$address) {
            $address = Db::name('address')->where(['uid' => $uid])->find();
        }
        $addressList = Db::name('address')->where(['uid' => $uid])->select();
        $this->assign('address', $address);
        $this->assign('addressList', $addressList);
        $this->assign('goods', $goods);
        $this->assign('title', '确认订单');
        return $this->view->fetch();
    }

    public function coupon()
    {
        if(request()->isAjax()) {
            $code = $this->request->param('code');
            if(!$code) {
                $this->error('请输入正确的优惠码');
            }
            $coupon = Db::name('coupon')->field('id,code,price,is_use')->where(['code' => $code])->find();
            if(!$coupon) {
                $this->error('优惠码不存在');
            }
            if($coupon['is_use']) {
                $this->error('优惠码已被使用');
            }
            $this->success('ok', '', $coupon);
        }
    }

}
